package com.chinacoal.microservice.mq;

import com.chinacoal.microservice.pojo.Message;
import com.chinacoal.microservice.util.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Description: 基于redis的消息队列
 * @author: 朱亮
 * @date: 2021年03月26日 9:28
 */
@Component
public class RedisMQ {

    /**
     * @Description: 消息池前缀，以此前缀加上传递的消息id作为key，以消息{@link Message} 的消息体body作为值存储
     * @author zhuliang
     * @date 2021/3/26 9:29
     */
    public static final String MSG_POOL = "Message:Pool:";

    /**
     * @Description: zset队列 名称 queue
     * @author zhuliang
     * @date 2021/3/26 9:30
     */
    public static final String QUEUE_NAME = "Message:Queue:";

    /**
     * @Description: 默认延时时间30秒
     * @author zhuliang
     * @date 2021/3/26 9:30
     */
    private static final int SEMIH = 30*60;



    @Autowired
    private RedisUtils redisUtils;


    /**
     * @Description: 存入消息池
     * @author zhuliang
     * @date 2021/3/26 9:30
     */
    public boolean addMsgPool(Message message) {

        if (null != message) {
            return redisUtils.setExp(MSG_POOL + message.getId(), message.getBody(), Long.valueOf(message.getTtl() + SEMIH));
        }
        return false;
    }


    /**
     * @Description: 从消息池中删除消息
     * @author zhuliang
     * @date 2021/3/26 9:31
     */
    public void deMsgPool(String id) {
        redisUtils.remove(MSG_POOL + id);
    }


    /**
     * @Description: 向队列中添加消息   score 优先级
     * @author zhuliang
     * @date 2021/3/26 9:31
     */
    public void enMessage(String key, long score, String val) {
        redisUtils.zsset(key,val,score);
    }


    /**
     * @Description: 从队列删除消息
     * @author zhuliang
     * @date 2021/3/26 9:31
     */
    public boolean deMessage(String key, String id) {
        return redisUtils.zdel(key, id);
    }
}
